package com.jiang.daily.Q1262;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Jiang
 * @version 1.0
 * @date 2025/11/23 18:18
 */
class Solution {
    // 贪心
    public int maxSumDivThree(int[] nums) {
        int s = 0;
        List<Integer> l1 = new ArrayList<>();
        List<Integer> l2 = new ArrayList<>();

        for (int n : nums) {
            if (n % 3 == 1) {
                l1.add(n);
            } else if (n % 3 == 2) {
                l2.add(n);
            }
            s += n;
        }

        if (s % 3 == 0) return s;

        Collections.sort(l1);
        Collections.sort(l2);


        // 这一步操作就不需要 频繁的判断（if (l1 == null) else if (l2 == null) else ）
        if (s % 3 == 2) {
            List<Integer> temp = l1;
            l1 = l2;
            l2 = temp;
        }
        int res = l1.isEmpty() ? 0 : s - l1.get(0);
        if (l2.size() > 1) res = Math.max(res, s - l2.get(0) - l2.get(1));

        return res;
    }
}
